<template>
  <div class="app-container">

    <el-form :model="param" :inline="true" label-width="68px">
      <el-form-item style="width:320px">
        <div>箱号</div>
        <MultipleBoxNumbersDialog v-model="param.containerNo"/>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>订单号</div>
        <el-input v-model.trim="param.orderNo" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>提箱日期</div>
        <el-date-picker v-model="param.planPickupDate" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>还箱日期</div>
        <el-date-picker v-model="param.returnDate" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>客户</div>
        <!-- <el-select v-model="param.createDate" /> -->
        <el-input v-model.trim="param.agentName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>发票状态</div>
        <!-- <el-select v-model="param.createDate" /> -->
        <el-select v-model="param.invoiceStatus" style="width:100%" placeholder="请选择">
          <el-option v-for="item in param.invoiceStatuss" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReSet" :icon="Refresh" style="margin-top: 30px">重置</el-button>
        <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">查询</el-button>
      </el-form-item>
    </el-form>

    <div>
      <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange"></cz-tages>
      <span style="margin-top: -40px;float: right;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有数据" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="selectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button :icon="Upload" type="primary" size="small" @click="toExportExcelData" plain>导出</el-button>
    </span>
      <Table ref="tableRef" v-bind="table" style="width: 100%;" :allId="allId" :isAllCheck="isAllCheck"
             @pageChange="onTablePageChange" @applyInvoice="applyInvoice"
             @updateSelectAll="updateSelectAll" @handleBuyBox="handleBuyBox"
             :disableHeaderCheckbox="disableHeaderCheckbox">
      </Table>
    </div>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible">
      <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>发票信息
      </div>
      <div style="height:180px;overflow: auto;margin-bottom: 10px">
        <invoice-template></invoice-template>
      </div>
      <el-form inline label-position="left" style="color: black;margin-bottom: 10px">
        <el-form-item label="发票状态:"><span style="color: green;">{{ '已开票' }}</span></el-form-item>
        <el-form-item label="发票内容:">{{ '待提箱' }}</el-form-item>
        <el-form-item label="发票抬头:">{{ '河南亚航国际货运代理有限公司' }}</el-form-item>
        <el-form-item label="联系电话:">{{ '15666666666' }}</el-form-item>
        <el-form-item label="在线咨询">
          <el-button type="primary" size="large" style="font-size: 15px;" link icon="ChatDotRound"></el-button>
        </el-form-item>
      </el-form>
      <div style="border:none;border-top: 1px solid #a6a9ad;padding: 10px 0 10px 0;">
        <el-form label-width="140px" label-position="left">
          <el-form-item label="发票类型">
            <el-radio-group v-model="rowData.invoiceType">
              <el-radio v-for="item in param.invoiceTypeList" :value="item.value" :key="item.value"
                        :label="item.label"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="企业名称">
            <el-input v-model="rowData.invoiceTitle" style="width: 400px;" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="统一社会信用代码">
            <el-input v-model="rowData.invoiceTaxNum" style="width: 400px;"
                      placeholder="请输入统一社会信用代码"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <el-form inline>
        <el-form-item label="应付箱量">28个</el-form-item>
        <el-form-item label="应付箱贴1费总计：">$970.36</el-form-item>
      </el-form>
      <el-table :data="table.data" style="width: 100%;">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="info" label="箱号" width="180"></el-table-column>
        <el-table-column prop="size" label="箱型" width="180"></el-table-column>
        <el-table-column prop="startCity" label="箱贴费（$）"></el-table-column>
        <el-table-column prop="startCity" label="超期天数"></el-table-column>
        <el-table-column prop="startCity" label="超期费（$）"></el-table-column>
        <el-table-column prop="startCity" label="应付箱贴费（$）"></el-table-column>
      </el-table>

      <div style="text-align: center;margin-top: 20px;">
        <el-checkbox v-model="param.radio">勾选后即同意买方应当在卖方开具发票之日起</el-checkbox>
        <div class="dialog-footer">
          <el-button @click="param.dialogVisible = false">取消</el-button>
          <el-button @click="handleApplyInvoice" type="primary">确认</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import {getAgentOrderReceivablePage, exportAgentReturnBox} from '@/api/boxCallBack/order'
import invoiceTemplate from '@/views/components/invoiceTemplate'
import {getTable, getBoxEastTable} from '@/api/orderManage/packing'

import {computed, onActivated, onMounted, reactive, ref} from 'vue';
import {
  Plus,
  Delete,
  Promotion,
  Edit,
  Message,
  Download,
  ChatDotRound, Finished, Upload
} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import {formatContainerNo} from '@/utils/mlpBox'
import {downloadFile} from '@/utils/download'

const param = reactive({
  radio: 0,
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: {5: '出租中', 10: '仓库中', 15: '待发布'},
  stateColor: {5: '#22A86D', 10: '#2158F3', 15: '#2158F3'},
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    {value: '5', label: '40HQ',},
    {value: '10', label: '40GP',},
    {value: '15', label: '20HQ',},
    {value: '20', label: '20GP',},
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    {value: '15', label: '适货',},
    {value: '10', label: '次新',},
    {value: '20', label: '混提',},
    {value: '5', label: '全新',},
  ],
  // invoiceStatus: 5, //发票状态
  invoiceStatuss: [
    {value: 5, label: '未申请'},
    {value: 10, label: '待开票'},
    {value: 15, label: '已开票'},
    {value: 20, label: '待红冲'},
    {value: 25, label: '已红冲'},
  ],
  invoiceStatusFilter: {'5': '未申请', '10': '待开票', '15': '已开票', '20': '待红冲', '25': '已红冲'}, //5-未申请  10-待开票  15-已开票
  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],
  overdueFeeCurrency: "$",
  invoiceTypeList: [{value: 5, label: '增值税普通发票'}, {value: 10, label: '增值税专用发票'}],
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    // { key: 'releaseRentId', colWidth: '220', title: 'releaseRentId', type: 'text', isCheck: true },
    // { key: 'id', colWidth: '220', title: 'ID', type: 'text', isCheck: true },
    {key: 'containerNo', colWidth: '200', title: '箱号', type: 'text', isCheck: true},
    {
      key: 'boxType',
      colWidth: '120',
      title: '箱型',
      type: 'filter',
      filter: {5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP'},
      isCheck: true
    },
    {
      key: 'unitPrice',
      colWidth: '100',
      title: '箱贴费',
      currency: 'priceCurrency',
      type: 'add',
      before: '$',
      isCheck: true
    },
    {key: 'companyName', colWidth: '200', title: '集装箱公司', type: 'text', isCheck: true},
    {key: 'createTime', colWidth: '200', title: '提箱日期', type: 'date', isCheck: true},
    {key: 'returnDate', colWidth: '200', title: '还箱日期', type: 'date', isCheck: true},
    {key: 'returnCityName', colWidth: '160', title: '还箱城市', type: 'text', isCheck: true},
    {key: 'boxUsagePeriod', colWidth: '120', title: '用箱天数', type: 'add', after: '天', isCheck: true},
    {key: 'overdueDays', colWidth: '120', title: '超期天数', type: 'add', after: '天', isCheck: true},
    {
      key: 'actualOverdueAmount',
      colWidth: '120',
      title: '超期费',
      type: 'add',
      currency: 'overdueFeeCurrency',
      isCheck: true
    },
    {
      key: 'invoiceStatus',
      colWidth: '120',
      title: '发票状态',
      type: 'filter',
      filter: param.invoiceStatusFilter,
      cFilter: param.stateColor,
      isCheck: true
    },
    // { key: 'status', colWidth: '120', title: '结算状态', type: 'filter', filter: param.stateFilter, cFilter: param.stateColor, isCheck: true },
    {key: 'orderNo', colWidth: '200', title: '订单号', type: 'text', isCheck: true, fixed: 'right',},
  ],
  stateColor: {5: '#2158F3', 10: '#2158F3', 15: '#22A86D'},
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

const rowData = ref({})

function getTableData() {
  const {container, containerList} = formatContainerNo(param.containerNo);
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    orderNo: param.orderNo,
    planPickupDate: param.planPickupDate,
    returnDate: param.returnDate,
    agentName: param.agentName,
    invoiceStatus: param.invoiceStatus
  };
  table.config.loading = true;
  // 获取列表数据
  getAgentOrderReceivablePage(data).then((res: any) => {
    table.data = JSON.parse(JSON.stringify(res.data.list));
    table.config.total = res.data.total;
  });
  table.config.loading = false;
}

// 重置
function handleReSet() {
  param.containerNo = null
  param.orderNo = null
  param.planPickupDate = null
  param.returnDate = null
  param.agentName = null
  getTableData()
}


//上架/下架  
const tableRef = ref({multipleSelection: []})
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})

//申请发票  
const applyInvoice = () => {
  if (selection.value.length == 0) {
    ElMessage.warning('请选择操作对象！')
    return
  }
  param.dialogVisible = true;
};
const handleApplyInvoice = () => {
  let ids = [...selection.value]
  console.log(ids)
  // deletePitch(ids).then((res: any) => {
  //   getTableData()
  // })
  param.dialogVisible = false;
};


//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

onActivated(() => {
  getTableData()
})


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const selectAll = async () => {
  checkAll.value = []
  let data = {
    pageNum: 1,
    pageSize: 10000,
  }
  await getAgentOrderReceivablePage(data).then(res => {
    if (res.code == "00000" && res.data.list && res.data.total) {
      isSelectAll.value = false
      disableHeaderCheckbox.value = true
      res.data.list.forEach(item => {
        checkAll.value.push(item)
      })
      isAllCheck.value = true
      allId.value = checkAll.value
      tableRef.value.checkAll()
    } else {
      ElMessage.error("全选失败，请刷新页面，或者手动选择")
    }
  })
}
const deselectAll = () => {
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
}


// 列表导出
const toExportExcelData = () => {
  let checkAllItem = []
  if (isSelectAll.value) {
    checkAllItem = tableRef.value.multipleSelection
  } else {
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
  if (ids.length < 1) return ElMessage.warning('请选择要导出的进口应收数据！')
  ElMessageBox.confirm('确认要导出选中的进口应收数据', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let reqParam = {"returnBoxListDetailIds": ids}
    exportAgentReturnBox(reqParam).then((res: any) => {
      downloadFile(res, '进口应收信息')
    }).catch((error: any) => {
      ElMessage.error(error)
    })
  }).catch(() => {
  });
}

</script>

<style scoped></style>